<?php
if (!defined('ABSPATH')) {
    exit;
}

$current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'config';

// 获取搜索引擎配置
global $wpdb;
$config_table = $wpdb->prefix . 'spider_push_config';
$engines = $wpdb->get_results("SELECT * FROM $config_table WHERE is_system = 1 ORDER BY engine_name");
$engine_map = array();
foreach ($engines as $e) { $engine_map[$e->engine_type] = $e; }


?>

<div class="wrap">
    <h1>URL自动推送</h1>
    
    <h2 class="nav-tab-wrapper">
        <a href="#push-config" class="nav-tab spa-tab-link <?php echo $current_tab === 'config' ? 'nav-tab-active' : ''; ?>" data-tab="config">
            推送配置
        </a>
        <a href="#push-manual" class="nav-tab spa-tab-link <?php echo $current_tab === 'manual' ? 'nav-tab-active' : ''; ?>" data-tab="manual">
            手动推送
        </a>
        <a href="#push-custom" class="nav-tab spa-tab-link <?php echo $current_tab === 'custom' ? 'nav-tab-active' : ''; ?>" data-tab="custom">
            自定义引擎
        </a>
    </h2>
    
    <div class="spider-push-content">
        <!-- 推送配置标签页 -->
        <div class="tab-panel" id="config-panel" style="display: <?php echo $current_tab === 'config' ? 'block' : 'none'; ?>;">
            <div class="card">
                <h3>🚀 5大主流搜索引擎推送配置</h3>
                <p>只需输入 Token/密钥 并启用，即可在发布文章时自动推送。</p>
                
                <form id="push-config-form">
                    <div class="engine-grid">
                        <?php
                        $defs = array(
                            array('type'=>'baidu','name'=>'百度','placeholder'=>'百度站长平台 Token'),
                            array('type'=>'bing','name'=>'必应 (IndexNow)','placeholder'=>'IndexNow Key'),
                            array('type'=>'google','name'=>'谷歌 Indexing API','placeholder'=>'服务账号密钥/令牌'),
                            array('type'=>'360','name'=>'360 搜索','placeholder'=>'360 Token'),
                            array('type'=>'bytedance','name'=>'字节（通用IndexNow）','placeholder'=>'IndexNow Key')
                        );
                        foreach ($defs as $d):
                            $row = isset($engine_map[$d['type']]) ? $engine_map[$d['type']] : null;
                            $enabled = $row ? intval($row->is_active) : 0;
                            $token = $row ? ($row->site_token ?: $row->api_key) : '';
                        ?>
                        <div class="engine-card" data-engine-type="<?php echo esc_attr($d['type']); ?>">
                            <div class="engine-left">
                                <div class="engine-logo" aria-hidden="true"></div>
                                <div class="engine-meta">
                                    <div class="engine-name"><?php echo esc_html($d['name']); ?></div>
                                    <div class="engine-desc">仅需填写 Token/密钥，接口已内置</div>
                                </div>
                            </div>
                            <div class="engine-right">
                                <label class="switch">
                                    <input type="checkbox" class="engine-enable" <?php checked($enabled,1); ?>>
                                    <span class="slider"></span>
                                </label>
                                <input type="text" class="engine-token" value="<?php echo esc_attr($token); ?>" placeholder="<?php echo esc_attr($d['placeholder']); ?>">
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <p class="submit">
                        <button type="submit" class="button button-primary">保存配置</button>
                    </p>
                </form>
            </div>
            
            
        </div>
        
        
        
        <!-- 手动推送标签页 -->
        <div class="tab-panel" id="manual-panel" style="display: <?php echo $current_tab === 'manual' ? 'block' : 'none'; ?>;">
            <div class="card">
                <h3>🔗 手动推送URL</h3>
                <form id="manual-push-form">
                    <table class="form-table">
                        <tr>
                            <th><label for="push-url">URL地址</label></th>
                            <td>
                                <input type="url" id="push-url" name="url" class="regular-text" 
                                       placeholder="https://example.com/post-title" required>
                                <p class="description">输入要推送的完整URL地址</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label>推送目标</label></th>
                            <td>
                                <?php 
                                $active_engines = array_filter($engines, function($e) { return $e->is_active; });
                                if (empty($active_engines)): 
                                ?>
                                    <p class="description">请先启用至少一个搜索引擎</p>
                                <?php else: ?>
                                    <ul>
                                    <?php foreach ($active_engines as $engine): ?>
                                        <li><?php echo esc_html($engine->engine_name); ?></li>
                                    <?php endforeach; ?>
                                    </ul>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>
                    
                    <p class="submit">
                        <button type="submit" class="button button-primary" 
                                <?php echo empty($active_engines) ? 'disabled' : ''; ?>>
                            立即推送
                        </button>
                    </p>
                </form>
                
                <div id="manual-push-result" style="display: none;">
                    <h4>推送结果</h4>
                    <div id="push-results"></div>
                </div>
            </div>
        </div>
        
        <!-- 自定义引擎标签页 -->
        <div class="tab-panel" id="custom-panel" style="display: <?php echo $current_tab === 'custom' ? 'block' : 'none'; ?>;">
            <div class="card">
                <h3>➕ 添加自定义搜索引擎</h3>
                <p>添加小众或自定义的搜索引擎推送接口。</p>
                
                <form id="add-custom-engine-form" class="form-table">
                    <table class="form-table">
                        <tr>
                            <th><label for="custom-engine-name">搜索引擎名称 *</label></th>
                            <td>
                                <input type="text" id="custom-engine-name" name="engine_name" class="regular-text" required>
                                <p class="description">例如：Yandex推送、DuckDuckGo推送等</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="custom-api-url">API接口地址 *</label></th>
                            <td>
                                <input type="url" id="custom-api-url" name="api_url" class="regular-text" required>
                                <p class="description">完整的推送接口URL，例如：https://api.example.com/push</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="custom-api-key">API密钥</label></th>
                            <td>
                                <input type="text" id="custom-api-key" name="api_key" class="regular-text">
                                <p class="description">可选，如果API需要身份验证</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="custom-push-method">请求方式</label></th>
                            <td>
                                <select id="custom-push-method" name="push_method">
                                    <option value="POST">POST</option>
                                    <option value="GET">GET</option>
                                </select>
                            </td>
                        </tr>
                    </table>
                    
                    <p class="submit">
                        <button type="submit" class="button button-primary">添加搜索引擎</button>
                    </p>
                </form>
            </div>
            
            <div class="card">
                <h3>📝 自定义搜索引擎列表</h3>
                <div id="custom-engines-list">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.spider-push-content {
    margin-top: 20px;
}

.card {
    background: #fff;
    border: 1px solid #ccd0d4;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
    margin-bottom: 20px;
    padding: 20px;
}

.card h3 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 1.3em;
}

.engine-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
    gap: 16px;
    margin: 10px 0 20px;
}
.engine-card { border: 1px solid #e1e5e9; border-radius: 12px; padding: 14px 16px; background: #fff; display: flex; align-items: center; justify-content: space-between; gap: 14px; transition: box-shadow .2s ease, transform .2s ease; }
.engine-card:hover { box-shadow: 0 6px 20px rgba(0,0,0,.06); transform: translateY(-1px); }
.engine-left { display: flex; align-items: center; gap: 12px; min-width: 170px; }
.engine-logo { width: 36px; height: 36px; border-radius: 10px; background: #f0f2f5; }
.engine-card[data-engine-type="baidu"] .engine-logo { background: linear-gradient(135deg,#287fff,#2da0ff); }
.engine-card[data-engine-type="bing"] .engine-logo { background: linear-gradient(135deg,#008373,#27c6a9); }
.engine-card[data-engine-type="google"] .engine-logo { background: linear-gradient(135deg,#4285F4,#34A853); }
.engine-card[data-engine-type="360"] .engine-logo { background: linear-gradient(135deg,#2ecc71,#27ae60); }
.engine-card[data-engine-type="bytedance"] .engine-logo { background: linear-gradient(135deg,#2d6cff,#00d1ff); }
.engine-meta { display: flex; flex-direction: column; gap: 2px; }
.engine-name { font-weight: 600; }
.engine-desc { font-size: 12px; color: #666; }
.engine-right { display: flex; align-items: center; gap: 12px; flex: 1; }
.engine-token { flex: 1; min-width: 180px; }

/* Switch */
.switch { position: relative; display: inline-block; width: 42px; height: 22px; }
.switch input { opacity: 0; width: 0; height: 0; }
.slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #c8cfd6; transition: .2s; border-radius: 22px; }
.slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 2px; bottom: 2px; background-color: white; transition: .2s; border-radius: 50%; }
.switch input:checked + .slider { background-color: #2271b1; }
.switch input:checked + .slider:before { transform: translateX(20px); }

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.stat-card {
    text-align: center;
    padding: 20px;
    background: #f9f9f9;
    border-radius: 4px;
}

.stat-number {
    font-size: 2em;
    font-weight: bold;
    color: #0073aa;
}

.stat-number.success {
    color: #46b450;
}

.stat-number.error {
    color: #dc3232;
}

.loading {
    text-align: center;
    padding: 40px;
    color: #666;
}

.pagination {
    margin: 20px 0;
    text-align: center;
}

.pagination button {
    margin: 0 5px;
}

#push-history-container table {
    margin-top: 20px;
}

.status-success {
    color: #46b450;
    font-weight: bold;
}

.status-failed {
    color: #dc3232;
    font-weight: bold;
}

.status-pending {
    color: #ffb900;
    font-weight: bold;
}

.test-result {
    margin: 10px 0;
    padding: 10px;
    border-left: 4px solid #ccc;
}

.test-result.success {
    border-left-color: #46b450;
    background: #f7fff7;
}

.test-result.error {
    border-left-color: #dc3232;
    background: #fff7f7;
}

@media screen and (max-width: 782px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .form-table th {
        padding-bottom: 5px;
    }
}
    .badge {
        display: inline-block;
        padding: 3px 8px;
        font-size: 12px;
        font-weight: 600;
        line-height: 1;
        border-radius: 10px;
    }
    .badge-custom {
        background-color: #0073aa;
        color: white;
    }
    .badge-success {
        background-color: #46b450;
        color: white;
    }
    .badge-warning {
        background-color: #ffb900;
        color: #444;
    }
    
    #custom-engines-list table {
        margin-top: 15px;
    }
    #custom-engines-list code {
        font-size: 12px;
        background: #f0f0f0;
        padding: 2px 5px;
    }
    
    /* SPA标签页样式 */
    .spa-tab-link {
        transition: all 0.3s ease;
        position: relative;
    }
    
    .spa-tab-link:hover {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white !important;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }
    
    .spa-tab-link.nav-tab-active {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        color: white !important;
        border-color: #4facfe;
    }
    
    .tab-panel {
        animation: fadeIn 0.3s ease-in-out;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
</style>

<script>
jQuery(document).ready(function($) {
    // SPA标签页切换
    $('.spa-tab-link').on('click', function(e) {
        e.preventDefault();
        const tab = $(this).data('tab');
        switchTab(tab);
    });
    
    // 切换标签页函数（修复未定义）
    function switchTab(tab) {
        // 隐藏所有标签页
        $('.tab-panel').hide();
        // 移除所有活动状态
        $('.spa-tab-link').removeClass('nav-tab-active');
        // 显示选中的标签页
        $('#' + tab + '-panel').show();
        // 添加活动状态
        $('.spa-tab-link[data-tab="' + tab + '"]').addClass('nav-tab-active');
        // 根据标签页加载相应数据
        if (tab === 'custom') { loadCustomEngines(); }
        if (tab === 'config') { loadSystemEngines(); }
    }

    // 加载系统引擎并填充UI（从数据表实时读取）
    function loadSystemEngines(){
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: { action: 'get_engines', nonce: (window.wpSpiderMonitor && wpSpiderMonitor.nonce) ? wpSpiderMonitor.nonce : '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>' }
        }).done(function(resp){
            if (!resp || !resp.success || !Array.isArray(resp.data)) { return; }
            var rows = resp.data.filter(function(r){ return String(r.is_system) === '1' || r.is_system === 1; });
            var map = {};
            rows.forEach(function(r){ map[r.engine_type] = r; });
            $('.engine-card').each(function(){
                var type = $(this).data('engine-type');
                var row = map[type];
                if (!row) { return; }
                var enabled = (row.is_active == 1 || row.is_active === '1');
                var token = row.site_token && row.site_token.length ? row.site_token : (row.api_key || '');
                $(this).find('.engine-enable').prop('checked', enabled);
                $(this).find('.engine-token').val(token);
            });
        });
    }

    // 保存配置
    $('#push-config-form').on('submit', function(e) {
        e.preventDefault();
        var formData = { action: 'save_push_config', nonce: wpSpiderMonitor.nonce, config: {} };
        $('.engine-card').each(function(){
            var type = $(this).data('engine-type');
            var enabled = $(this).find('.engine-enable').is(':checked') ? 1 : 0;
            var token = $(this).find('.engine-token').val().trim();
            formData.config[type] = { enabled: enabled, token: token };
        });
        var $submitBtn = $(this).find('button[type="submit"]');
        var originalText = $submitBtn.text();
        $submitBtn.text('保存中...').prop('disabled', true);
        $.ajax({ url: ajaxurl, type: 'POST', dataType: 'json', data: formData })
        .done(function(response){
            try {
                if (response && response.success) { showNotification(response.data || '保存成功', 'success'); }
                else { showNotification((response && response.data) ? response.data : '保存失败', 'error'); }
            } catch(err) { console.error('push-config success handler error:', err); showNotification('保存结果处理异常', 'error'); }
        })
        .fail(function(xhr, status){ console.warn('push-config request failed:', status, xhr && xhr.responseText); showNotification('保存失败，请重试', 'error'); })
        .always(function(){ $submitBtn.text(originalText).prop('disabled', false); loadSystemEngines(); });
    });
    
    // 简化：保存后即生效，如需测试可后续补加接口
    
    // 初始化当前标签页数据
    const currentTab = '<?php echo $current_tab; ?>';
    if (currentTab === 'custom') { loadCustomEngines(); }
    if (currentTab === 'config') { loadSystemEngines(); }
    
    
    // 手动推送
    $('#manual-push-form').on('submit', function(e) {
        e.preventDefault();
        
        var url = $('#push-url').val();
        if (!url) {
            showNotification('请输入URL', 'error');
            return;
        }
        
        var $submitBtn = $(this).find('button[type="submit"]');
        var originalText = $submitBtn.text();
        $submitBtn.text('推送中...').prop('disabled', true);
        
        $.post(ajaxurl, {
            action: 'manual_push_url',
            nonce: wpSpiderMonitor.nonce,
            url: url
        }, function(response) {
            if (response.success) {
                $('#manual-push-result').show();
                var resultsHtml = '';
                response.data.forEach(function(result) {
                    resultsHtml += '<div class="push-result ' + (result.result.success ? 'success' : 'error') + '">';
                    resultsHtml += '<strong>' + result.engine + ':</strong> ';
                    resultsHtml += result.result.success ? '推送成功' : '推送失败: ' + result.result.error;
                    resultsHtml += '</div>';
                });
                $('#push-results').html(resultsHtml);
                
                // 清空输入
                $('#push-url').val('');
            } else {
                showNotification(response.data, 'error');
            }
        }).fail(function() {
            showNotification('推送失败，请重试', 'error');
        }).always(function() {
            $submitBtn.text(originalText).prop('disabled', false);
        });
    });
    
    // 自定义引擎管理
    if ($('#add-custom-engine-form').length) {
        
        // 添加自定义引擎
        $('#add-custom-engine-form').on('submit', function(e) {
            e.preventDefault();
            
            var formData = {
                engine_name: $('#custom-engine-name').val().trim(),
                api_url: $('#custom-api-url').val().trim(),
                api_key: $('#custom-api-key').val().trim(),
                push_method: $('#custom-push-method').val()
            };
            
            if (!formData.engine_name || !formData.api_url) {
                showNotification('请填写必填字段', 'error');
                return;
            }
            
            var $button = $(this).find('button[type="submit"]');
            var originalText = $button.text();
            
            $button.prop('disabled', true).text('添加中...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                            action: 'add_custom_engine',
                            engine_name: formData.engine_name,
                            api_url: formData.api_url,
                            api_key: formData.api_key,
                            push_method: formData.push_method,
                            nonce: wpSpiderMonitor.nonce
                        },
                success: function(response) {
                    if (response.success) {
                        showNotification('搜索引擎添加成功！', 'success');
                        $('#add-custom-engine-form')[0].reset();
                        loadCustomEngines();
                    } else {
                        showNotification(response.data || '添加失败', 'error');
                    }
                },
                error: function() {
                    showNotification('请求失败，请重试', 'error');
                },
                complete: function() {
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });
    }
    
    // 加载自定义引擎列表
    function loadCustomEngines() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'get_engines',
                nonce: (window.wpSpiderMonitor && wpSpiderMonitor.nonce) ? wpSpiderMonitor.nonce : '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    displayCustomEngines(response.data);
                } else {
                    $('#custom-engines-list').html('<p>加载失败</p>');
                }
            },
            error: function() {
                $('#custom-engines-list').html('<p>加载失败</p>');
            }
        });
    }
    
    // 显示自定义引擎列表
    function displayCustomEngines(engines) {
        var $container = $('#custom-engines-list');
        
        if (!engines || engines.length === 0) {
            $container.html('<p>暂无自定义搜索引擎</p>');
            return;
        }
        
        var html = '<table class="wp-list-table widefat fixed striped">';
        html += '<thead><tr>';
        html += '<th>搜索引擎</th>';
        html += '<th>API接口</th>';
        html += '<th>状态</th>';
        html += '<th>操作</th>';
        html += '</tr></thead><tbody>';
        
        engines.forEach(function(engine) {
            html += '<tr>';
            html += '<td><strong>' + escapeHtml(engine.engine_name) + '</strong></td>';
            html += '<td><code>' + escapeHtml(engine.api_url) + '</code></td>';
            html += '<td>' + (engine.is_active ? '<span style="color:green">启用</span>' : '<span style="color:red">禁用</span>') + '</td>';
            html += '<td>';
            html += '<button class="button button-small delete-engine" data-id="' + engine.id + '">删除</button>';
            html += '</td>';
            html += '</tr>';
        });
        
        html += '</tbody></table>';
        $container.html(html);
        
        // 绑定删除事件
        $('.delete-engine').on('click', function() {
            var engineId = $(this).data('id');
            if (confirm('确定要删除这个搜索引擎吗？')) {
                deleteCustomEngine(engineId);
            }
        });
    }
    
    // 删除自定义引擎
    function deleteCustomEngine(engineId) {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'delete_engine',
                engine_id: engineId,
                nonce: (window.wpSpiderMonitor && wpSpiderMonitor.nonce) ? wpSpiderMonitor.nonce : '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    showNotification('搜索引擎删除成功！', 'success');
                    loadCustomEngines();
                } else {
                    showNotification(response.data || '删除失败', 'error');
                }
            },
            error: function() {
                showNotification('请求失败，请重试', 'error');
            }
        });
    }
    
    // HTML转义函数
    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    function showNotification(message, type) {
        var $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>');
        $('.wrap').prepend($notice);
        
        setTimeout(function() {
            $notice.fadeOut(function() {
                $notice.remove();
            });
        }, 3000);
    }
});
</script>